/**
 * Created by duwei on 2019/2/21.
 */
var ZiPai_JieSuanWindow = JieSuanWindow.extend({
    _ccsFileName: zipai.res.ZiPai_JieSuanWindow_json,
    _cardSize:35,
    _initInfo: function () {
        var self = this;
        this.huInfo = ZiPaiRoomData.gameOverHuInfo;
        self._setWanFa();
        self._setTime();
        self._setRoomId();
        self._setPlayers();
        self._setTitle();
        self._setDipai();
        self._setBtn();
    },
    /**
     * 设置玩法名称
     * @private
     */
    _setWanFa: function () {
        var self = this;
        var wanfa = (gameData.mapId ? ('玩法：' + gameData.mapId2Name(gameData.mapId)) : '玩法：');
        this._nodeList["root.lb_name"].setString(wanfa);
        this._nodeList["root.lb_wanfa"].setString(gameData.wanfaDesp);
    },
    /**
     * 设置时间
     * @private
     */
    _setTime: function () {
        var self = this;
        self._nodeList["root.lb_ts"].setString(self._data['EndTime']);
    },
    /**
     * 设置房间号/局数
     */
    _setRoomId: function () {
        var self = this;
        var roomIdStr = '房号：' + gameData.roomId + '   局数：' + gameData.curRound + '/' + gameData.totalRound;
        self._nodeList["root.lb_roomid"].setString(roomIdStr);
    },
    /**
     * 设置玩家数据
     * @private
     */
    _setPlayers: function () {
        var self = this;
        this.myturn = 0;
        this.winnerturn = 0;
        self.Winner = self._data['Winner'];
        self._nodeList["root.player2"].setVisible(gameData.playerNum == 2);
        self._nodeList["root.player3"].setVisible(gameData.playerNum == 3);
        self.playerNode = self._nodeList["root.player" + gameData.playerNum];

        var players = deepCopy(self._data['Users']);
        if (self.Winner) {
            for (var i = 0; i < players.length; i++) {
                var player = players[0];
                if (player['UserID'] != self.Winner) {
                    players.splice(0, 1);
                    players.push(player);
                }
                else
                    break;
            }
        }

        for (var i = 0; i < players.length; i++) {
            var player = players[i];
            var uid = player['UserID'];
            var score = player['Result'];
            if (uid == gameData.uid) {
                self.my_score = score;
                self.myturn = i + 1;
            }
            if (uid == self._data['Winner']) {
                this.winnerturn = i + 1;
            }
            self._setRowUnit(i, player);
        }
    },
    /**
     * 设置玩家牌数据
     * @param index
     * @param player
     * @private
     */
    _setRowUnit: function (index, player) {
        var self = this;
        var uid = player.UserID;
        var playerInfo = gameData.getPlayerInfoByUid(uid);
        var RowUnit = self.playerNode["Player" + index];
        RowUnit['playerNode']["lb_name"].setString(ellipsisStr(playerInfo['nickname'], 6));
        RowUnit['playerNode']["lb_id"].setString('ID:' + uid);
        loadHeadImage(playerInfo['headimgurl'], RowUnit['playerNode']['head'], true);//头像
        RowUnit['bg_ziji'] && RowUnit['bg_ziji'].setVisible(self.Winner && (index == 0));
        self._setRowCard(index, player);
        self.setMingTang(index);

        // var Result = player['Result'] ? player['Result'] : 0;
        // RowUnit["txtScore"].setString('得分:' + (Result > 0 ? ('+' + Result) : Result));
        // var zhuangUid = self._data['Banker'];
        // RowUnit["zhuang"].setVisible(zhuangUid == uid);
        //
        // if (player['SmallTiLong'] || player['BigTiLong']) {
        //     RowUnit['ti'].setString('提龙:' + (player['SmallTiLong'] || 0) + '小/' + (player['BigTiLong'] || 0) + '大');
        // } else {
        //     RowUnit['ti'].setVisible(false);
        // }
        // //点炮
        // var dianpao = RowUnit["dianpao"];
        // var ByWho = self._data['ByWho'];
        // if (ByWho && ByWho == uid) {
        //     dianpao.setVisible(true);
        // } else {
        //     dianpao.setVisible(false);
        // }
        // //赢家
        // var Winner = self._data['Winner'];
        // if (Winner && Winner == uid) {
        //     dianpao.setTexture(zipai.dynamicRes + 'roomclean/hu.png');
        //     dianpao.setVisible(true);
        // }
        //
        // var win = RowUnit['win'];
        // if (Result > 0) {
        //     win.setTexture(zipai.dynamicRes + 'result/win.png');
        // } else if (Result == 0) {
        //     win.setTexture(zipai.dynamicRes + 'result/ping.png');
        // } else {
        //     win.setTexture(zipai.dynamicRes + 'result/lose.png');
        // }
    },
    /**
     * 获取牌组件
     * @param row
     * @param index
     * @returns {*|cc.Node|ccui.Widget}
     */
    getComBoInfoNode: function (row, index) {
        var self = this;
        var RowUnit = self.playerNode["Player" + row];
        var nCombos = RowUnit['nCombos'];
        var ComBoInfo0 = nCombos['ComBoInfo0'];

        var ComBoInfoNode = nCombos.getChildByName('ComBoInfo' + index);
        if (!ComBoInfoNode) {
            ComBoInfoNode = duplicateNode(ComBoInfo0);
            ComBoInfoNode.setName('ComBoInfo' + index);
            ComBoInfoNode.setPositionX(ComBoInfo0.getPositionX() + index * 380 / 8);
            nCombos.addChild(ComBoInfoNode);
        }
        var pai_hu =ComBoInfoNode.getChildByName('pai_hu');
        pai_hu.setVisible(false);
        pai_hu.posY = pai_hu.getPositionY();
        var posNode = ComBoInfoNode.getChildByName('posNode');
        posNode.removeAllChildren();
        return ComBoInfoNode;
    },
    /**
     * 设置门子
     * @param row
     * @param index
     * @param comboInfo
     * @param ByCard
     */
    setComBoInfo: function (row, index, comboInfo,ByCard) {
        var self = this;
        var ComBoInfoNode = self.getComBoInfoNode(row, index);
        var posNode = ComBoInfoNode.getChildByName('posNode');
        for (var k = 0; k < comboInfo['Cards'].length; k++) {
            var cardNo = comboInfo['Cards'][k];
            var card = new Card();
            card.setData(cardNo, null, 2);
            card.setScale(self._cardSize / 42);
            card.setAnchorPoint(0, 0);
            card.setPosition(0, k * self._cardSize);
            posNode.addChild(card);
            if(ByCard){
                card.index = k;
                self.winCards.push(card);
            }
        }
        ComBoInfoNode.getChildByName('type').setVisible(comboInfo['Cards'].length > 2);
        ComBoInfoNode.getChildByName('huxi').setVisible(comboInfo['Cards'].length > 2);
        ComBoInfoNode.getChildByName('type').setString(comboInfo['Type']);
        ComBoInfoNode.getChildByName('huxi').setString(comboInfo['Xi']);
    },
    /**
     * 设置手牌
     * @param row
     * @param index
     * @param Hands
     */
    setShouPaiInfo: function (row, index, Hands,shoupaiHuxi) {
        var self = this;
        var CardList = mCard.getCardList(Hands);
        CardList.sort(function (a, b) {
            return b.length - a.length;
        });
        var ComBoInfoNode = self.getComBoInfoNode(row, index);
        var posNode = ComBoInfoNode.getChildByName('posNode');
        for (var i = 0; i < CardList.length; i++) {
            var Cards = CardList[i];
            for (var k = 0; k < Cards.length; k++) {
                var cardNo = Cards[k];
                var card = new Card();
                card.setData(cardNo, null, 2);
                card.setScale(self._cardSize / 42);
                card.setAnchorPoint(0, 0);
                card.setPosition(i * self._cardSize, k * self._cardSize);
                posNode.addChild(card);
            }
        }
        ComBoInfoNode.getChildByName('type').setString('手牌');
        if(shoupaiHuxi){
            ComBoInfoNode.getChildByName('huxi').setString(shoupaiHuxi);
        }else {
            ComBoInfoNode.getChildByName('huxi').setVisible(false);
        }

    },
    /**
     * 设置弃牌
     * @param row
     * @param DiscardCards
     */
    setQiPaiInfo: function (row, DiscardCards) {
        var self = this;
        var RowUnit = self.playerNode["Player" + row];
        var qipaiNode = RowUnit['qipaiNode'];
        var qipaiPos = qipaiNode['qipaiPos'];
        if(DiscardCards && DiscardCards.length>0){
            for (var k = 0; k < DiscardCards.length; k++) {
                var cardNo = DiscardCards[k];
                var card = new Card();
                card.setData(cardNo, null, 2);
                card.setScale(self._cardSize / 42);
                card.setAnchorPoint(0, 0);
                card.setPosition((k % 7) * self._cardSize, -parseInt(k / 7) * self._cardSize);
                qipaiPos.addChild(card);
            }
        }
    },
    /**
     * 设置胡牌牌型
     */
    _setComboList: function (index, player) {
        var self = this;
        if (self.huInfo == null) {
            return;
        }
        var comboList = [];
        if (self.huInfo.openList) {
            for (var i = 0; i < self.huInfo.openList.length; i++) {
                comboList.push(self.huInfo.openList[i]);
            }
        }
        if (self.huInfo.kanList) {
            for (var i = 0; i < self.huInfo.kanList.length; i++) {
                comboList.push(self.huInfo.kanList[i]);
            }
        }
        if (self.huInfo.huList) {
            for (var i = 0; i < self.huInfo.huList.length; i++) {
                comboList.push(self.huInfo.huList[i]);
            }
        }
        comboList.sort(function (a, b) {
            return b.cards.length - a.cards.length;
        });
        self.winCards = [];
        for (var i = 0; i < comboList.length; i++) {
            var comboInfo = comboList[i];
            var cInfo = {};
            cInfo['Cards'] = comboInfo['cards'];
            cInfo['Type'] = mCard.comboName[comboInfo.typ - 1];
            cInfo['Xi'] = mCard.getComboHuXi(comboInfo);
            self.setComBoInfo(index, i, cInfo, self._data['ByCard']);
        }
        if (self.winCards.length > 0) {
            for (var s = self.winCards.length - 1; s >= 0; s--) {
                var card = self.winCards[s];
                if (self._data['ByCard'] && self._data['ByCard'] == card.data) {
                    var ComBoInfoNode = card.getParent().getParent();
                    var hu_icon = ComBoInfoNode.getChildByName('pai_hu');
                    hu_icon.setVisible(true);
                    hu_icon.setPositionY(hu_icon.posY +  card.index * self._cardSize);
                    break;
                }
            }
        }
        self.setFenShu(index, player, true);
    },
    /**
     * 设置玩家显示位置
     * @private
     */
    _setRowCard: function (index, player) {
        var self = this;
        var RowUnit = self.playerNode["Player" + index];
        var AllCards = player['AllCards'];
        var DiscardCards = AllCards['DiscardCards'];
        var Hands = AllCards['Hands'];
        var Menzi = AllCards['Menzi'];
        var nCombos = RowUnit['nCombos'];
        var ComBoInfo0 = nCombos['ComBoInfo0'];
        var count = 0;
        var huxi = 0;
        if (self.Winner && index == 0) {
            self._setComboList(index, player);
        } else {
            //门子
            if(Menzi && Menzi.length>0){
                for (var i = 0; i < Menzi.length; i++) {
                    var mz = Menzi[i];
                    if (mz.Type == '吃') {
                        //吃的牌特殊显示
                        var chiCard = mz['Chi'];
                        for (var k = 0; k < mz['Cards'].length; k += 3) {
                            var cards = [mz['Cards'][k], mz['Cards'][k + 1], mz['Cards'][k + 2]];
                            var typ = mCard.getComboType(cards, false);
                            //吃的放在第一个位置
                            for (var x = 0; x < cards.length; x++) {
                                if (chiCard == cards[x]) {
                                    var tmp = cards[x];
                                    for (var y = x + 1; y < 3; y++) {
                                        cards[y - 1] = cards[y];
                                    }
                                    cards[2] = tmp;
                                }
                            }
                            var comboInfo = {};
                            comboInfo['Cards'] = cards;
                            comboInfo['Type'] = mz.Type;
                            comboInfo['Xi'] = mCard.getComboHuXi({cards: cards, typ: typ});
                            huxi += comboInfo['Xi'];
                            self.setComBoInfo(index, count, comboInfo);
                            count++;
                        }
                    } else if (mz.Type == '话') {
                        for (var k = 0; k < mz['Cards'].length; k += 3) {
                            var cards = [mz['Cards'][k], mz['Cards'][k + 1], mz['Cards'][k + 2]];
                            var typ = mCard.getComboType(cards, false);
                            var comboInfo = {};
                            comboInfo['Cards'] = cards;
                            comboInfo['Type'] = mz.Type;
                            comboInfo['Xi'] = mCard.getComboHuXi({cards: cards, typ: typ});
                            huxi += comboInfo['Xi'];
                            self.setComBoInfo(index, count, comboInfo);
                            count++;
                        }
                    } else {
                        var typ = mCard.comboTypes_ZN[mz.Type];
                        var comboInfo = {};
                        comboInfo['Cards'] = mz['Cards'];
                        comboInfo['Type'] = mz.Type;
                        comboInfo['Xi'] = mCard.getComboHuXi({cards: mz['Cards'], typ: typ});
                        huxi += comboInfo['Xi'];
                        self.setComBoInfo(index, count, comboInfo);
                        count++;
                    }
                }
            }
            var CardList = mCard.getCardList(Hands);
            huxi += mCard.getHandsHuXi(CardList);
            self.setShouPaiInfo(index, count, Hands);
            player['HuXi'] = huxi;
            self.setFenShu(index, player);
        }
        //弃牌
        self.setQiPaiInfo(index, DiscardCards);
    },
    /**
     * 设置底牌
     * @private
     */
    _setDipai: function () {
        var count = 12;
        var self = this;
        var LeftCards = self._data['LeftCards'];
        var Sipai = self._data['Sipai'];
        var dipaiNode = self._nodeList['root.dipaiNode'];
        dipaiNode['bg2'].setVisible(gameData.playerNum == 2);
        dipaiNode['bg3'].setVisible(gameData.playerNum == 3);
        dipaiNode['choupaiNode'].setVisible(gameData.playerNum == 2 && Sipai && Sipai.length > 0);

        for (var i = 0; i < LeftCards.length; i++) {
            var x = i % count;
            var y = parseInt(i / count);
            var card = new Card();
            card.setData(LeftCards[i], null, 2);
            card.setScale(self._cardSize / 42);
            card.setAnchorPoint(0, 0);
            card.setPosition(x * self._cardSize, y * -35);
            dipaiNode['dipaiPos0'].addChild(card);

            if(i == LeftCards.length-1){
                var di_icon = duplicateNode(dipaiNode['pai_di']);
                di_icon.setVisible(true);
                di_icon.setPosition(x * self._cardSize, y * -35);
                dipaiNode['dipaiPos0'].addChild(di_icon);
            }
        }
        if (Sipai && Sipai.length > 0) {
            for (var i = 0; i < Sipai.length; i++) {
                var x = i % count;
                var y = parseInt(i / count);
                var card = new Card();
                card.setData(Sipai[i], null, 2);
                card.setScale(self._cardSize / 42);
                card.setAnchorPoint(0, 0);
                card.setPosition(x * self._cardSize, y * -35);
                dipaiNode['choupaiNode']['choupaiPos0'].addChild(card);
            }
        }
    },
    setFenShuColor: function (node, num) {
        node.setColor((parseInt(num)) >= 0 ? cc.color('B30000') : cc.color("065a00"));
        node.setString(num);
    },
    /**
     * 设置分数
     * @private
     */
    setFenShu: function (index, player, isWinner) {
        var self = this;
        var RowUnit = self.playerNode["Player" + index];
        var tunshu = RowUnit['tunshu'];//囤数
        var fanshu = RowUnit['fanshu'];//番数
        var huxi = RowUnit['huxi'];//胡息
        var fenshu = RowUnit['fenshu'];//分数

        var lb_tunshu = RowUnit['lb_tunshu'];//囤数
        var lb_fanshu = RowUnit['lb_fanshu'];//番数
        var lb_huxi = RowUnit['lb_huxi'];//胡息
        var lb_fenshu = RowUnit['lb_fenshu'];//分数

        tunshu.setVisible(isWinner);
        fanshu.setVisible(isWinner);
        lb_tunshu.setVisible(isWinner);
        lb_fanshu.setVisible(isWinner);

        if (isWinner) {
            self.setFenShuColor(lb_tunshu, self._data['WinnerTun']);
            self.setFenShuColor(lb_fanshu, self._data['WinnerFan']);
            self.setFenShuColor(lb_huxi, self._data['WinnerXi']);
            self.setFenShuColor(lb_fenshu, player['Result']);
        } else {
            self.setFenShuColor(lb_huxi, player['HuXi']);
            self.setFenShuColor(lb_fenshu, player['Result']);
        }
    },
    /**
     * 设置标题
     * @private
     */
    _setTitle: function () {
        var self = this;
        var shengli = this._nodeList['root.shengli'];
        var shibai = this._nodeList['root.shibai'];
        var huanghzuang = this._nodeList['root.huanghzuang'];
        var isHuangzhuang = (self._data['LeftCards'].length == 0 && self._data['Winner'] == 0 && self._data['ByCard'] == 0);
        huanghzuang.setVisible(isHuangzhuang);
        if (isHuangzhuang) {
            shengli.setVisible(false);
            shibai.setVisible(false);
        } else {
            shengli.setVisible(self._data['Winner'] == gameData.uid);
            shibai.setVisible(self._data['Winner'] != gameData.uid);
        }
    },
    /**
     * 设置名堂
     * @private
     */
    setMingTang: function (index) {
        var self = this;
        var flag = self._data['FanFlag'];
        var flag2 = self._data['FanFlag2'];
        var FanRemark = self._data['FanRemark'].split(",");
        //FanRemark = ['碰碰胡','海底胡','红胡','点胡'];
        var RowUnit = self.playerNode["Player" + index];
        var mingTangNode = RowUnit['mingTangNode'];
        if (!mingTangNode) {
            return;
        }
        var isMingTang = (index == 0 && FanRemark.length > 0);
        mingTangNode.setVisible(isMingTang);
        var mingtang0 = mingTangNode['mingtang0'];
        mingtang0.setVisible(false);
        if (isMingTang) {
            for (var i = 0; i < FanRemark.length; i++) {
                if (FanRemark[i] == '') {
                    break;
                }
                var mingtang = mingTangNode.getChildByName('mingtang' + i);
                if (!mingtang) {
                    mingtang = duplicateNode(mingtang0);
                    mingtang.setPosition(cc.p(0 -parseInt(i/5)*160, -(i%5) * 65));
                    mingTangNode.addChild(mingtang);
                }
                mingtang.setVisible(true);
                mingtang.setString(FanRemark[i]);
                var size = mingtang.getContentSize();
                mingtang['kuang'].setContentSize(cc.size(size.width + 40, size.height + 15));
                mingtang['kuang'].setPosition(cc.p(size.width / 2, size.height / 2));
            }
        }
    },
    /**
     * 设置按钮状态
     */
    _setBtn: function () {
        var self = this;
        var panelResult = this._nodeList['root.PanelResult'];
        panelResult.setVisible(true);
        var btn_result_bg = panelResult['btn_result_bg'];
        var checkResult = btn_result_bg['checkResult'];
        var checkResultbg = btn_result_bg['checkResultbg'];
        var showTable = btn_result_bg['showTable'];
        var showTablebg = btn_result_bg['showTablebg'];
        var jixu = panelResult['continue'];

        TouchUtil.setOnclickListener(checkResult, function () {
            self.removeFromParent();
        });
        TouchUtil.setOnclickListener(showTable, function () {
            self.removeFromParent();
        });
        TouchUtil.setOnclickListener(jixu, function () {
            if (ZiPaiRoomData.isReplay) {
                self.removeFromParent();
            } else {
                self._room.showRoomClean();
                self._room.onReady();
                self.removeFromParent();
            }
        });
    },
})
